import * as cornerstoneTools from '@cornerstonejs/tools'
import { ref, watch } from 'vue'
import { IMG_OP_NAME, IMG_OP_NAME_RESET, IMG_OP_NOT_TOOL_NAME, OP_TOOLS_MAP } from '@/types/viewSetting'

const {
  ToolGroupManager
} = cornerstoneTools

function useInitToolGroup(toolGroupId = 'toolGroup', handleReset = {}, handleNotToolOp = {}) {
  const activeOp = ref('')
  let preActive = IMG_OP_NAME.None

  function _resetOpTools() {
    const tool = OP_TOOLS_MAP[preActive]
    if (tool) {
      toolGroup.setToolPassive(tool.tool.toolName)
    }
  }

  function _handleClickResetBtn(newOp) {
    handleReset[newOp]()
    activeOp.value = IMG_OP_NAME.None
  }

  function _toggleTools(newOp, newActiveTool, oldActiveTool) {
    const isMobile = window.matchMedia('(any-pointer:coarse)').matches
    if (newActiveTool) {
      preActive = newOp
      toolGroup.setToolActive(newActiveTool.tool.toolName, newActiveTool.toolBindingsOptions)
    }
    if (oldActiveTool) {
      toolGroup.setToolPassive(oldActiveTool.tool.toolName)
    }
  }

  watch(activeOp, (newOp, oldOp) => {
    if (IMG_OP_NOT_TOOL_NAME[newOp]) {
      handleNotToolOp[IMG_OP_NOT_TOOL_NAME[newOp]]()
      return
    }
    if (newOp === IMG_OP_NAME.None) {
      _resetOpTools()
      return
    }
    const newActiveTool = OP_TOOLS_MAP[newOp]
    const oldActiveTool = OP_TOOLS_MAP[oldOp]
    if (IMG_OP_NAME_RESET[newOp]) {
      _handleClickResetBtn(newOp)
      return
    }
    _toggleTools(newOp, newActiveTool, oldActiveTool)
  })
  let toolGroup = ToolGroupManager.getToolGroup(toolGroupId)
  if (!toolGroup) {
    toolGroup = ToolGroupManager.createToolGroup(toolGroupId)
  }
  const setActive = val => {
    if (activeOp.value === val && IMG_OP_NOT_TOOL_NAME[val]) {
      handleNotToolOp[IMG_OP_NOT_TOOL_NAME[val]]()
      return
    }
    activeOp.value = val
    updateTool()
  }

  const updateTool = () => {
    const activeTool = OP_TOOLS_MAP[activeOp.value]
    if (activeTool) {
      toolGroup.setToolActive(activeTool.tool.toolName, activeTool.toolBindingsOptions)
    }
  }

  const addTools2Render = (viewportId, renderingEngineId) => {
    toolGroup.addViewport(viewportId, renderingEngineId)
  }


  return {
    toolGroup,
    activeOp,
    setActive,
    addTools2Render
  }
}

export {
  useInitToolGroup
}
